<!-- 定向派福分 -->
<template>
  <a-drawer
    v-model:visible="vdata.visible"
    width="40%"
    :mask-closable="false"
    @close="close"
  >
    <template #title>
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <span>导入名单</span>
      </div>
    </template>

    <div class="container">
      <a-form
        ref="formRef"
        layout="vertical"
        :model="vdata.saveObject"
        :label-col="{ span: 24 }"
        :wrapper-col="{ span: 24 }"
        class="form"
        :rules="rules"
      >
        <a-row>
          <a-col :span="12">
            <a-form-item label="小程序归属机构" name="agentNo" :wrapper-col="{ span: 18 }">
              <GzTreeSelect ref="gzThreeRef" v-model:value="vdata.saveObject['agentNo']" :showLevel="3" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="微信小程序" name="appId" :wrapper-col="{ span: 18 }">
              <!-- <a-select v-model:value="vdata.saveObject['appId']" :options="vdata.saveObject['agentNo'] ? officialList : []" placeholder="请选择微信公众号" /> -->
              <a-select v-model:value="vdata.saveObject['appId']" placeholder="选择小程序" @change="changehandle">
                <a-select-option v-for="item in smallProgramlist" :key="item.appId" :value="item.appId">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item name="fileList">
              <template #label>
                <span style="margin-right: 20px">文件上传</span>
                <a-button
                  class="item"
                  type="link"
                  style="padding: 4px 0"
                  @click="downloadTemplate"
                >
                  导入名单模板下载
                </a-button>
              </template>
              <a-upload-dragger
                v-model:fileList="vdata.saveObject['fileList']"
                :action="vdata['action']"
                :data="vdata.formParams"
                :maxCount="1"
                accept=".xlsx, .xls"
                name="file"
                :beforeUpload="beforeUpload"
                @change="uploadChange"
              >
                <p class="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p class="ant-upload-text">拖动到此处上传，或<a>点击上传</a></p>
                <p class="ant-upload-hint">
                  <b style="color: #ff4d4f">每次只能上传一个文件，</b>限制文件格式为XLS/XLSX。
                </p>
              </a-upload-dragger>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- 列表展示 -->
      <!-- <GzTable
        ref="infoTableRef"
        :table-columns="tableColumns"
        :pagination="true"
        :scrollX="600"
        :dataSource="resultList"
      /> -->
    </div>
  </a-drawer>
</template>
<script lang="ts" setup>
import { ref, reactive, getCurrentInstance, defineExpose,onMounted,watch } from 'vue'
import {$apiAgentAppList} from '@/api/activityManage/activityList/index'
import * as XLSX from 'xlsx'
import {
  req,
  $getUploadFormParams,
  API_ACTIVITY_DISPOSABLEIMPORT,
} from '@/api/manage'

const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties

const infoTableRef = ref()
// 数据源
const vdata: any = reactive({
  visible: false, //是否显示
  action: '', //上传地址
  fileList: [], //上传文件列表
  saveObject: {},
})

const formRef = ref()

const smallProgramlist = ref()
// 获取小程序列表
// 获取小程序列表
function  getLiteBannerList(data) {
  $apiAgentAppList(data).then(res => {
    console.log(res,88888)
    smallProgramlist.value = res
  })
}

const rules = {
  appId: [{ required: true, message: '请选择小程序', trigger: 'change' }],
  agentNo:[{ required: true, message: '请选择机构', trigger: 'change' }],
  fileList: [{ required: true, message: '请上传文件', trigger: 'change' }],
}

// 监听机构变化 重新请求小程序/公众号列表
watch(() => vdata.saveObject.agentNo, async (newVal) => {
  if (newVal) {
    console.log(newVal,'newVal')
    getLiteBannerList({type: 1,agentNo:newVal})
  }
})

function changehandle(val) {
  console.log(val,'选择的小程序是那个')
  vdata.saveObject.appId = val
  // 根据val找到对应的小程序
  // const selectedProgram = smallProgramlist.value.find(item => item.appId === val)
  //  vdata.saveObject.agentNo = selectedProgram ? selectedProgram.agentNo : ''
}
// 列表表头
const tableColumns = [
  { key: 'openid', title: '小程序openid', dataIndex: 'openid' },
  { key: 'phone', title: '手机号', dataIndex: 'phone' },
  { key: 'scoreValue', title: '积分值', dataIndex: 'scoreValue' },
  { key: 'overDays', title: '过期天数', dataIndex: 'overDays' },
  { key: 'result', title: '导入结果', dataIndex: 'result' },
]

/**
 * 文件上传
 */
async function beforeUpload(file) {
  // 校验内容是否填写
  await formRef.value.validate()  // 表单校验
  // 校验文件大小 不大于20MB
  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isLt20M) {
    $infoBox.message.warn('文件大小不能超过20MB！')
    return false
  }
  // 校验文件格式
  const isExcel = /\.(xlsx|xls)$/.test(file.name)
  if (!isExcel) {
    $infoBox.message.warn('文件格式必须为XLS/XLSX！')
    return false
  }
  return $getUploadFormParams(file, 'upload').then((res) => {
    vdata.action = res.formActionUrl // action
    vdata.formParams = res.formParams //表单组件
    vdata.saveObject.ossFileUrl = res.ossFileUrl
  })
}
function uploadChange(info) {
  if (info.file.status === 'error') {
    // 上传异常
    vdata.saveObject.fileList = []
    $infoBox.message.error('上传异常,请联系系统管理员')
  }

  if (info.file.status === 'done') {
    // 上传成功
    complete()
  }
}
const resultList = ref([])

// 完成
function complete() {
  req
    .add(API_ACTIVITY_DISPOSABLEIMPORT, {
      activityId: vdata.saveObject.activityId,
      ossFileUrl: vdata.saveObject.ossFileUrl,
      appId:vdata.saveObject.appId
    })
    .then((res, error) => {
      // resultList.value = res
          const url = res
          const link = document.createElement('a')
          link.href = url
          link.download = 'filename.xlsx' // 设置下载文件名
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
      // 刷新渠道列表
      $infoBox.message.success('导入成功')
    })
}

// excel表格导出函数数据
const exportToExcel = (item, name) => {
  // 创建一个工作簿
  const workbook = XLSX.utils.book_new()
  // 创建一个工作表
  const worksheet = XLSX.utils.aoa_to_sheet(item)
  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
  // 生成Excel文件
  XLSX.writeFile(workbook, `${name}.xlsx`)
}

// 模板下载
function downloadTemplate() {
  let tempalteInformation: any = undefined
  let tempalteName: any
  tempalteName = '导入名单模板'
  tempalteInformation = [
    ['小程序openid', '手机号', '积分值', '过期天数'],
    ['DGxg******Klv5', '137*******567', '20', '60'],
  ]
  exportToExcel(tempalteInformation, tempalteName)
}

/**
 * 展开
 */
async function show(record) {
  vdata.saveObject = {
    activityId: record.activityId,
    // agentNo:vdata.saveObject.agentNo
  }
  
  vdata.visible = true
  // 获取小程序列表
  // getLiteBannerList()
}
function close() {
  vdata.visible = false
}

defineExpose({
  show,
})
</script>
<style lang="less" scoped>
.choseText {
  color: #1890ff;
}

.container {
  width: 100%;
  padding-bottom: 30px;

  .textMerchant {
    width: 60%;
    margin-bottom: 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .merchantResult {
    .information {
      display: flex;
      justify-content: right;
      margin-top: 30px;
    }
  }

  .form {
    margin: 30px;
    justify-content: center;
    overflow-y: auto;

    &::-webkit-scrollbar {
      display: none;
    }
  }
}

/deep/ .ant-upload-list-item-name {
  width: auto;
  flex-grow: 1 !important;
}
</style>
